package cn.iune.controllers;

import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.iune.backcenter.author.ISaOporgService;
import cn.iune.backcenter.author.SaOporg;
import cn.iune.backcenter.author.sysinfo.ISysInfoService;
import cn.iune.config.MyRealm;
import cn.iune.config.SecurityService;


@Controller
public class AppcenterController {
	
	@Autowired
	private ISaOporgService saOporgService;
	
	@Autowired
	private ISysInfoService sysInfoService;
	
	
	@Autowired
	private MyRealm myRealm1;
	
	
	//根据输入的人员成员ID进行授权，如果ID不存在，则跳转到登录界面
	@RequestMapping(value="/appcenter/frame",method=RequestMethod.GET)
	public ModelAndView appcenterView(@RequestParam(value="access_token",required=false) String access_token, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("/appcenter/frame");
//		mav.addObject("activityId", "aactivityId");  
//		mav.addObject("ognName", ognName); 
//		mav.addObject("psmid", psmid); 
		return mav;
	}
	
	//获取授权，根据输入的人员成员ID进行授权，如果ID不存在，则跳转到登录界面
	@RequestMapping(value="/grant",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject grant(@RequestBody(required=false) JSONObject data) {
		System.out.println(">>>>/appcenter/grant加载！"+data.toJSONString());
		
//		SaOporg psm = saOporgService.getByID(psmID);
		SaOporg psm = null;
		if(data.getJSONObject("psm")==null) {
			//首次加载，获取默认的人员成员（只有唯一一个）
			System.out.println(">>>>/appcenter/grant加载！输入参数为空！");
			psm = SecurityService.getCurrentPsm();
			if(psm==null) {
				//表示存在多个人员成员，需要在前台显示备选
				JSONObject json = new JSONObject();
				json.put("code", 1);
				json.put("status", "success");
				return json;
			}
		}else {
			//在前台选择人员成员
			psm = JSON.toJavaObject(data.getJSONObject("psm"), SaOporg.class);
			System.out.println(">>>>/appcenter/grant加载！"+psm.getsFName());
			SecurityService.setCurrentPsm(psm);
			
			////////////////////加载公司及公司所绑定的应用/////////////////////////
    		//根据当前人员成员获取当前公司（最近的上级公司）
    		SaOporg topOgn = saOporgService.getCompany(SecurityService.getCurrentPsm());
    		SecurityService.setCurrentOgn(topOgn);
    		
			SecurityService.setCurrentAppId("appId");
			SecurityService.setCurrentAppName("云逸ERP-U2");

    		////////////////////////////////////////////////////////////////////////////

		}
		
		//在此重新授权（按组织机构）

		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		
		myRealm1.clearCachedAuthorizationInfo(principals);
		//下面这两个函数的区别：第一个函数可以独立使用，第二个函数必须与上面的函数配合使用
//		AuthorizationInfo info = myRealm1.doGetAuthorizationInfo(principals);//1
		AuthorizationInfo info = myRealm1.getAuthorizationInfo(principals);//2
		
		//打印当前人员成员的角色列表
		Collection<String> realmRoles = info.getRoles();
//		System.out.println("当前人员成员拥有的角色列表如下：");
//		for(String r:realmRoles){
//        	System.out.println("role------------------->"+r);
//		}
		
		Collection<String> realmPerms = info.getStringPermissions();
//		System.out.println("当前人员成员拥有的权限列表如下：");
//		for(String p:realmPerms){
//        	System.out.println("permission------------------->"+p);
//		}
		


		
		String psmid = null;
		String sName = null;
		String sFName = null;
		
		if(psm!=null){
			psmid = psm.getsID();
			sName = psm.getsName();
			sFName = psm.getsFName();
		}
		
		String ognName = null;
		SaOporg ogn = SecurityService.getCurrentOgn();
		if(ogn!=null) {
			ognName = ogn.getsName();
			
		}
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("status", "success");
		
		json.put("ognName", ognName); 
		
		json.put("psmid", psmid); 
		json.put("sFName", sFName);
		json.put("sName", sName);
		
		json.put("roles", realmRoles);
		json.put("perms", realmPerms);

		return json;
	}
	
	
	//获取人员成员列表
	@RequestMapping(value = "/getPsmList", method = RequestMethod.GET)
	@ResponseBody
	public List<SaOporg> getPsmList(@RequestParam(value="cid",required=false) String cid,HttpServletRequest request) {
		String userId = SecurityService.getCurrentPerson().getString("userId");
//		String orgID = SecurityService.getCurrentOgn().getsID();
//		System.out.println("orgID-->>"+orgID);
		return saOporgService.getByPersonID(userId);
//		return saOporgService.getPersonMembers(userId, orgID);
	}

	//更改当前身份
	/*
	 * @RequestMapping(value="/appcenter/changePsm",method=RequestMethod.POST)
	 * 
	 * @ResponseBody public JSONObject changePsm(@RequestBody JSONObject data) {
	 * SaOporg psm = JSON.toJavaObject(data, SaOporg.class);
	 * SecurityService.setCurrentPsm(psm); SaOporg topOgn =
	 * saOporgService.getCompany(SecurityService.getCurrentPsm());
	 * SecurityService.setCurrentOgn(topOgn);
	 * 
	 * JSONObject json = new JSONObject(); json.put("code", 0); json.put("status",
	 * "success"); return json; }
	 */

    //信息面板
	@RequestMapping(value="/center/center",method=RequestMethod.GET)
	public ModelAndView centerView(){
		ModelAndView mav = new ModelAndView("/appcenter/center/center");
		mav.addObject("path", "/center/center");
		return mav;
	}

//	@RequestMapping(value="/sysInfo/getTreeMenu",method=RequestMethod.GET)
	@ResponseBody
	public JSONObject getTreeMenu0()  {
		System.out.println("加载菜单0......");
		
		//打印当前人员成员的角色列表
//		Set<String> realmRoles = SecurityService.getRealmRoles();
//		System.out.println("当前人员成员拥有的角色列表如下：");
//		for(String r:realmRoles){
//        	System.out.println("role------------------->"+r);
//		}
		
		//System.out.println("sysInfoCache.getSysInfoJson()-->>"+sysInfoCache.getSysInfoJson().toJSONString());
		//首先转换为字符串，然后再转换成json，是为了避免sysInfoCache.getSysInfoJson()被关联改变
//		String jsonStr = sysInfoCache.getSysInfoJson().toJSONString();
//		JSONObject json = JSONObject.parseObject(jsonStr);
		
        String appId = SecurityService.getCurrentAppId();
		//加载全部树形菜单列表
		JSONObject param = new JSONObject();
//		String columns = EntityToDefColJSON.doit(SysInfo.class);
//		JSONObject col = JSONObject.parseObject(columns);
//		param.put("columns", col);
		param.put("offset", 0);
		param.put("limit", -1);
		String filter = "SysInfo.appId='"+appId+"'";
		param.put("filter", filter);
		param.put("orderBy", "sortNo ASC");
		JSONObject json = sysInfoService.queryData(param);
		//System.out.println("sysInfoJson-->>"+sysInfoJson.toJSONString());
		System.out.println("加载系统信息");
		
		json.put("appId", appId);

		
		//获取树形JSON的rows
		JSONObject data = json.getJSONObject("data");
		JSONArray rows = data.getJSONArray("rows");
		JSONArray rowsNew = new JSONArray();
		for(int i=0;i<rows.size();i++) {
			JSONObject row = rows.getJSONObject(i);
			//System.out.println("getTreeMenu0-->>"+row.toJSONString());
//			String fID = row.getJSONObject("fID").getString("value");
			String absoluteUrl = row.getJSONObject("absoluteUrl").getString("value");
			String systemFullID = row.getJSONObject("systemFullID").getString("value");
			System.out.println("getTreeMenu0-->>"+absoluteUrl+"-->>"+systemFullID);
			
			
			//查找是否存在匹配的
//			for(int x=0;x<ids.size();x++){
//				String id = ids.get(x);
//				if(id.equals(fID)) {
//					//System.out.println("找到匹配项目-->>"+fID+"-->>"+row.getJSONObject("systemFullName").getString("value"));
//					//rows.remove(i);
//					rowsNew.add(row);
//					break;
//				}
//			}
		}
		
//		json.getJSONObject("data").put("rows", new JSONArray());
//		for(int i=0;i<rowsNew.size();i++) {
//			System.out.println("getTreeMenu2-->>"+rowsNew.getJSONObject(i).toJSONString());
//		}
		json.getJSONObject("data").put("rows", rowsNew);
		
		return json;
	}

	@RequestMapping(value="/sysInfo/getTreeMenu",method=RequestMethod.GET)
	@ResponseBody
	public JSONObject getTreeMenu()  {
		System.out.println("加载树形菜单......");
		
		//增加用登录用户获取的ids
		List<String> ids = (List<String>) SecurityService.getTreeNavigation();
		if(ids==null) {
			JSONObject json = new JSONObject();
			json.put("code", 1);
			json.put("msg", "菜单ids为空！");
			return json;
		}else {
//			for(int x=0;x<ids.size();x++){
//				String id = ids.get(x);
//				System.out.println("打印ids列表-->>"+id);
//			}
		}

		
		//System.out.println("sysInfoCache.getSysInfoJson()-->>"+sysInfoCache.getSysInfoJson().toJSONString());
		//首先转换为字符串，然后再转换成json，是为了避免sysInfoCache.getSysInfoJson()被关联改变
//		String jsonStr = sysInfoCache.getSysInfoJson().toJSONString();
//		JSONObject json = JSONObject.parseObject(jsonStr);
		
        String appId = SecurityService.getCurrentAppId();
		//加载全部树形菜单列表
        
		JSONObject param = new JSONObject();
//		String columns = EntityToDefColJSON.doit(SysInfo.class);
//		JSONObject col = JSONObject.parseObject(columns);
//		param.put("columns", col);
		param.put("offset", 0);
		param.put("limit", -1);
		String filter = "SysInfo.appId='"+appId+"'";
		param.put("filter", filter);
		param.put("orderBy", "sortNo ASC");
		JSONObject json = sysInfoService.queryData(param);
		
//		String orgID = SecurityService.getCurrentOgn().getsID();
//		JSONObject json = sysInfoService.getTreeMenuData(appId, orgID);
		System.out.println("sysInfoJson-->>"+json.toJSONString());
		System.out.println("加载系统信息");
		
		json.put("appId", appId);

		
		//获取树形JSON的rows
		JSONObject data = json.getJSONObject("data");
		JSONArray rows = data.getJSONArray("rows");
		JSONArray rowsNew = new JSONArray();
		for(int i=0;i<rows.size();i++) {
			JSONObject row = rows.getJSONObject(i);
			//System.out.println("getTreeMenu-->>"+row.toJSONString());
			String fID = row.getJSONObject("fID").getString("value");
			//查找是否存在匹配的
			for(int x=0;x<ids.size();x++){
				String id = ids.get(x);
				if(id.equals(fID)) {
					//System.out.println("找到匹配项目-->>"+fID+"-->>"+row.getJSONObject("systemFullName").getString("value"));
					//rows.remove(i);
					rowsNew.add(row);
					break;
				}
			}
		}
		
//		json.getJSONObject("data").put("rows", new JSONArray());
//		for(int i=0;i<rowsNew.size();i++) {
//			System.out.println("getTreeMenu2-->>"+rowsNew.getJSONObject(i).toJSONString());
//		}
		json.getJSONObject("data").put("rows", rowsNew);
		
		return json;
	}

	
	
	
	
	
	
	
	
	
	
	
	
	


}
